<?php

namespace App\Http\Controllers\group;

use App\Models\Commission;
use App\Models\GroupMember;
use App\Models\User;
use Illuminate\Support\Carbon;

class IncomeController extends BaseController
{
    public function preview()
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        $userId = $user->getAttribute('id');
        // 总收入
        $total = Commission::query()
            ->where('user_id', $userId)
            ->sum('user_money');

        // 获取昨日收入 yesterday
        $yesterdayStart = Carbon::yesterday()->startOfDay();
        $yesterdayEnd = Carbon::yesterday()->endOfDay();
        $yesterday = Commission::query()
            ->where('user_id', $userId)
            ->whereBetween('child_user_withdraw_at', [$yesterdayStart, $yesterdayEnd])
            ->sum('user_money');

        // 获取今日收入 today
        $todayStart = Carbon::today()->startOfDay();
        $today = Commission::query()
            ->where('user_id', $userId)
            ->where('child_user_withdraw_at', '>=', $todayStart)
            ->sum('user_money');

        return $this->success([
            'total' => $total,
            'yesterday' => $yesterday,
            'today' => $today,
        ]);
    }


    public function detail()
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        $userId = $user->getAttribute('id');

        // 总收入
        $total = Commission::query()
            ->where('user_id', $userId)
            ->sum('user_money');

        // 获取用户的收入详情按天列出
        $details = Commission::query()
            ->selectRaw('DATE(child_user_withdraw_at) as date, SUM(user_money) as total_income, source')
            ->where('user_id', $userId)
            ->groupBy('date', 'source')
            ->orderBy('date', 'desc')
            ->get();

        $members = GroupMember::query()
            ->selectRaw('DATE(joined_at) as date, count(*) as count')
            ->where('leader_id', $userId)
            ->groupBy('date')
            ->orderBy('date', 'desc')
            ->get();

        // 将结果格式化为所需的结构
        $formattedDetails = $details->map(function($detail) use ($members) {
            $member = $members->where('date', $detail->date)->first();
            return [
                'date' => $detail->date,
                'total_income' => $detail->total_income,
                'team_income' => $detail->total_income,
                'source' => $detail->source,
                'new_member' => $member->count ?? 0,
            ];
        });

        return $this->success([
            'total' => $total,
            'details' => $formattedDetails,
        ]);
    }
}
